package com.ruoyi.sale.service.impl;

import com.ruoyi.audit.domain.Audit;
import com.ruoyi.audit.mapper.AuditMapper;
import com.ruoyi.audit.service.AuditService;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.product.domain.Product;
import com.ruoyi.product.domain.ProductModel;
import com.ruoyi.purchase.domain.PurchaseModel;
import com.ruoyi.purchase.domain.PurchaseOrder;
import com.ruoyi.purchase.mapper.PurchaseOrderMapper;
import com.ruoyi.sale.domain.SaleGoodsOrder;
import com.ruoyi.sale.domain.SaleorderModel;
import com.ruoyi.sale.domain.SaleorderOrder;
import com.ruoyi.sale.mapper.SaleorderMapper;
import com.ruoyi.sale.service.ISaleGoodsService;
import com.ruoyi.sale.service.ISaleorderService;
import com.ruoyi.warehousing.domain.Warehousing;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author WangChangShuo
 * @date 2022年05月09日 17:42
 */
@Service
public class SaleorderServiceImpl implements ISaleorderService {

    @Autowired
    SaleorderMapper saleorderMapper;

    @Autowired
    AuditMapper auditMapper;

    @Autowired
    PurchaseOrderMapper purchaseOrderMapper;

    /**
     * 查询销售订单列表
     *
     * @param saleorderOrder
     * @return
     */
    @Override
    public List<SaleorderOrder> selectSaleorderOrderList(SaleorderOrder saleorderOrder) {
        return saleorderMapper.selectSaleorderOrderList(saleorderOrder);
    }


    /**
     * 查询产品型号规格集合
     *
     * @param map 查询条件
     * @return 结果
     */
    @Override
    public List<ProductModel> selectProductList(Map map) {
        return saleorderMapper.selectProductList(map);
    }

    /**
     * 通过产品的型号唯一码查询产品子表数据
     *
     * @param hashMap 查询条件
     * @return 结果
     */
    @Override
    public ProductModel selectProductModelByModelCode(HashMap<String, Object> hashMap) {
        return saleorderMapper.selectProductModelByModelCode(hashMap);
    }

    /**
     * 通过产品的型号唯一码查询产品子表数据
     *
     * @param modelCode 查询条件
     * @return 结果
     */

    /**
     * 插入销售订单数据
     *
     * @param saleorderOrder 需要插入的数据
     * @return 结果
     */
    @Transactional
    @Override
    public int insertSaleorder(SaleorderOrder saleorderOrder) {
        return saleorderMapper.insertSaleorder(saleorderOrder);
    }

    /**
     * 查询采购订单列表数据
     *
     * @param hashMap 查询条件
     * @return 结果
     */
    @Override
    public List<PurchaseModel> selectPurchaseModelById(HashMap hashMap) {
        return saleorderMapper.selectPurchaseModelById(hashMap);
    }

    /**
     * 插入销售订单子集数据
     *
     * @param saleorderOrder 需要插入的数据
     * @return 结果
     */
    @Transactional
    @Override
    public int insertSaleorderModel(SaleorderOrder saleorderOrder) {
        return saleorderMapper.insertSaleorderModel(saleorderOrder);
    }

    /**
     * 修改采购订单的是否生成销售订单的状态
     *
     * @param hashMap 修改条件
     * @return 结果
     */
    @Transactional
    @Override
    public int updatePurchaseIsCreateSale(HashMap hashMap) {
        return saleorderMapper.updatePurchaseIsCreateSale(hashMap);
    }

    /**
     * 查询采购订单集合数据
     *
     * @param purchaseOrder 查询条件
     * @return 结果
     */
    @Override
    public List<PurchaseOrder> selectPurchaseOrderList(PurchaseOrder purchaseOrder) {
        return saleorderMapper.selectPurchaseOrderList(purchaseOrder);
    }

    /**
     * 查询采购订单的集合数据
     *
     * @param purchaseOrder 查询条件
     * @return 结果
     */
    @Override
    public List<PurchaseOrder> selectPurchaseOrderListWithDe(PurchaseOrder purchaseOrder) {
        return saleorderMapper.selectPurchaseOrderListWithDe(purchaseOrder);
    }

    /**
     * 查询主表子表数据 以及做该销售订单之前的 执行数量和 剩余数量
     *
     * @param hashMap 查询条件
     * @return 结果
     */
    @Override
    public SaleorderOrder selectSaleorderById(HashMap<String, Object> hashMap) {
        return saleorderMapper.selectSaleorderById(hashMap);
    }

    /**
     * 修改销售订单
     *
     * @param saleorderOrder 销售订单信息
     * @return 改变的行数
     */
    @Transactional
    @Override
    public int updateSaleorderOrder(SaleorderOrder saleorderOrder, PurchaseOrder purchaseOrder) {

        //修改审核表
        Audit audit = new Audit();
        //销售订单为0
        audit.setOrderType("0");
        //业务员
        audit.setUserId(saleorderOrder.getSaleorderUserId());
        //客户 公司id
        audit.setSupplierId(saleorderOrder.getCompanyId());
        //含税金额
        audit.setTaxAmount(saleorderOrder.getSaleorderTaxamount());

        //订单id
        audit.setOrderId(saleorderOrder.getSaleorderId());
        //订单编号
        audit.setOrderNum(saleorderOrder.getSaleorderNum());
        auditMapper.updateAuditOther(audit);
        //判断子表 是否为空
        if (saleorderOrder.getSaleorderModels() != null) {
            //不为空 查询自己 用来做比较
            List<SaleorderModel> saleorderModels = saleorderOrder.getSaleorderModels();
            //新建对比数组，用于判断执行什么操作
            ArrayList<Long> arrayList = new ArrayList();
            //根据销售订单id  查询 原来的自己的数据
            Long saleorderId = saleorderOrder.getSaleorderId();
            List<SaleorderModel> saleorderModels1 = saleorderMapper.selectSaleModelById(saleorderId);
            for (int i = 0; i < saleorderModels.size(); i++) {
                saleorderModels.get(i).setSaleorderId(saleorderOrder.getSaleorderId());
            }
            for (SaleorderModel model : saleorderModels1) {
                arrayList.add(model.getSaleorderModelId());
            }
            ArrayList<Long> saleorderModelList = new ArrayList();
            for (SaleorderModel model : saleorderModels) {
                if (model.getSaleorderModelId() != null) {
                    model.setRemainingNum(model.getAllNum());
                    saleorderMapper.updateSaleorderModel(model);
                    saleorderModelList.add(model.getSaleorderModelId());
                } else {
                    model.setRemainingNum(model.getAllNum());
                    model.setExecuteNum(0);
                    saleorderMapper.insertSaleorderModels(model);
                }
            }
            //数组中剩余的数就是需要删除的数据
            for (Long o1 : saleorderModelList) {
                Iterator<Long> iterator = arrayList.iterator();
                while (iterator.hasNext()) {
                    if (iterator.next().equals(o1)) {
                        iterator.remove();
                    }
                }
            }
            if (arrayList.size() != 0) {
                saleorderMapper.deleteSaleorderModelById(arrayList);
            }
        }
        if (purchaseOrder.getPurchaseModel() != null) {
            for (int j = 0; j < purchaseOrder.getPurchaseModel().size(); j++) {
                PurchaseModel purchaseModel = purchaseOrder.getPurchaseModel().get(j);
                //执行数量
                purchaseModel.setExecuteNum(purchaseModel.getExecuteNum() + purchaseModel.getPurchaseNum());
                //可执行数量
                Long remainingNum = purchaseModel.getRemainingNum() - purchaseModel.getPurchaseNum();
                purchaseModel.setRemainingNum(remainingNum);
                purchaseModel.setPurchaseNum(-1);
                purchaseOrderMapper.updatePurchaseModel(purchaseModel);
            }
        }
        return saleorderMapper.updateSaleorder(saleorderOrder);
    }

    /**
     * 根据订单主键 删除 主表以及子表
     *
     * @param saleorderId 销售订单主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteSaleOrderById(Long saleorderId) {

        HashMap hashMap = new HashMap();
        hashMap.put("orderId", saleorderId);
        hashMap.put("orderType", 0);
        auditMapper.deleteAuditWith(hashMap);

        //将选中的采购单 is_createSale 状态更改为0
        HashMap map = new HashMap();
        map.put("saleorderId", saleorderId);
        SaleorderOrder saleorderOrder = saleorderMapper.selectSaleorderById(map);
        PurchaseOrder purchaseOrder = new PurchaseOrder();
        purchaseOrder.setPurchaseId(saleorderOrder.getPurchaseId());
        purchaseOrderMapper.updatePurchaseOrderIsCreateSale(purchaseOrder);

        if (saleorderMapper.selectSaleModelIdById(saleorderId).size() != 0) {
            saleorderMapper.deleteSaleorderModelById(saleorderMapper.selectSaleModelIdById(saleorderId));
        }
        //若该销售订单选择了采购单 则将选中的采购单的执行数量剩余数量更新回去
        if (saleorderOrder.getPurchaseId() != null && !saleorderOrder.getSaleorderStatus().equals("2")) {
            for (int i = 0; i < saleorderOrder.getSaleorderModels().size(); i++) {
                SaleorderModel model = saleorderOrder.getSaleorderModels().get(i);
                PurchaseModel purchaseModel = new PurchaseModel();
                purchaseModel.setModelId(model.getPurchaseModelId());
                purchaseModel.setExecuteNum((long) model.getPurExecuteNum());
                purchaseModel.setRemainingNum((long) model.getPurRemainingNum());
                purchaseModel.setAllNum(model.getAllNum() + purchaseModel.getAllNum());
                purchaseModel.setPurchaseNum(-1);
                purchaseOrderMapper.updatePurchaseModel(purchaseModel);
            }
        }
        return saleorderMapper.deleteSaleOrderById(saleorderId);
    }

    /**
     * 查询产品的子集集合
     *
     * @param map 查询条件
     * @return 结果0
     */
    @Override
    public List<ProductModel> selectTableList(HashMap map) {
        return saleorderMapper.selectTableList(map);
    }

    @Override
    public List<ProductModel> selectMateTableList(HashMap map) {
        return saleorderMapper.selectMateTableList(map);
    }

    /**
     * 查询销售订单的数据
     *
     * @param saleorderOrder 查询条件
     * @return 结果
     */
    @Override
    public List<SaleorderOrder> selectSaleorderOrderListByStatusIsOne(SaleorderOrder saleorderOrder) {
        return saleorderMapper.selectSaleorderOrderListByStatusIsOne(saleorderOrder);
    }

    /**
     * 查询库存数据
     *
     * @param hashMap 查询条件
     * @return 结果
     */
    @Override
    public List<Warehousing> selectWarehousing(HashMap<String, Object> hashMap) {
        return saleorderMapper.selectWarehousing(hashMap);
    }

    /**
     * 修改销售订单中是否生成销货单的状态
     *
     * @param saleorderOrder 修改数据
     * @return 结果
     */
    @Override
    public int updateSaleorderIsCreateGoods(SaleorderOrder saleorderOrder) {
        return saleorderMapper.updateSaleorderIsCreateGoods(saleorderOrder);
    }

    /**
     * 通过公司主键查询销售订单的数据
     *
     * @param companyId 查询条件
     * @return 结果
     */
    @Override
    public List<SaleorderOrder> selectSaleorderDeptObj(Long companyId) {
        return saleorderMapper.selectSaleorderDeptObj(companyId);
    }

    /**
     * 查询上次订单的单价
     *
     * @param hashMap 查询条件
     * @return 结果
     */
    @Override
    public List<BigDecimal> selectSaleorderNewPrice(HashMap hashMap) {
        return saleorderMapper.selectSaleorderNewPrice(hashMap);
    }

    /**
     * 查询上次订单的单价
     *
     * @param hashMap 查询条件
     * @return 结果
     */
    @Override
    public List<BigDecimal> selectSaleorderNewPrices(HashMap hashMap) {
        return saleorderMapper.selectSaleorderNewPrices(hashMap);
    }

    /**
     * 根据公司主键查询客户信息
     *
     * @param companyId 公司主键
     * @return 结果
     */
    @Override
    public List<SaleorderOrder> selectSaleGoodsSupplierObj(Long companyId) {
        return saleorderMapper.selectSaleGoodsSupplierObj(companyId);
    }

    /**
     * 查询采购订单客户信息
     *
     * @param map 查询条件
     * @return 结果
     */
    @Override
    public List<SaleorderOrder> selectSaleGoodsSupplierObjMap(Map<String, Object> map) {
        return saleorderMapper.selectSaleGoodsSupplierObjMap(map);
    }

    /**
     * 根据公司主键查询订单信息
     *
     * @param saleorderOrder 查询条件
     * @return 结果
     */
    @Override
    public List<SaleorderOrder> selectSaleorderCustObj(SaleorderOrder saleorderOrder) {
        return saleorderMapper.selectSaleorderCustObj(saleorderOrder);
    }

    /**
     * 修改销售订单数据
     *
     * @param saleorderOrder 需要修改的数据
     * @return 结果
     */
    @Override
    public int updateSaleorderOrderIsPay(SaleorderOrder saleorderOrder) {
        return saleorderMapper.updateSaleorder(saleorderOrder);
    }

    /**
     * 查询销售订单信息
     *
     * @param hashMap 查询条件
     * @return 结果
     */
    @Override
    public List<SaleorderOrder> selectSaleGoodsByMap(Map<String, Object> hashMap) {
        return saleorderMapper.selectSaleGoodsByMap(hashMap);
    }

    /**
     * 查询销售订单主键
     *
     * @param companyId 公司主键
     * @return 结果
     */
    @Override
    public List<Long> selectById(Long companyId) {
        return saleorderMapper.selectById(companyId);
    }

    /**
     * 修改销售订单的合同数据
     *
     * @param saleorderOrder1 修改的数据
     * @return 结果
     */
    @Override
    public int updateSaleorderPdf(SaleorderOrder saleorderOrder1) {
        return saleorderMapper.updateSaleorderPdf(saleorderOrder1);
    }

    /**
     * 查询销售订单的信息集合
     *
     * @param saleorderId 销售订单主键
     * @return 结果
     */
    @Override
    public List<Product> selectSaleOrderModelById(Long saleorderId) {
        return saleorderMapper.selectSaleOrderModelById(saleorderId);
    }

    /**
     * 修改销售订单数据
     *
     * @param saleorderOrder1 需要修改的数据
     * @return 结果
     */
    @Override
    public int updateSaleorder(SaleorderOrder saleorderOrder1) {
        return saleorderMapper.updateSaleorder(saleorderOrder1);
    }

    /**
     * 通过主表id查询 子表信息
     *
     * @return 结果
     */
    @Override
    public List<SaleorderModel> selectBySaleorderIdList(List<Long> saleorderIdList) {
        return saleorderMapper.selectBySaleorderIdList(saleorderIdList);
    }

    /**
     * 查询销售订单子表数据集合
     *
     * @param rows 查询条件
     * @return 结果
     */
    @Override
    public List<SaleorderModel> selectModelDataByModelId(String rows) {
        String[] split = rows.split(",");
        List<SaleorderModel> list = saleorderMapper.selectModelByModelId(split);
        return list;
    }

    /**
     * 修改销售订单子表数据
     *
     * @param saleorderModel 修改的数据
     * @return 结果
     */
    @Override
    public void updateSaleorderModel(SaleorderModel saleorderModel) {
        saleorderMapper.updateSaleorderModel(saleorderModel);
    }

    /**
     * 查询销售订单主表数据
     *
     * @param order 查询条件
     * @return 结果
     */
    @Override
    public List<SaleorderOrder> selectOrder(SaleorderOrder order) {
        return saleorderMapper.selectOrder(order);
    }

    /**
     * 查询销售订单子表数据集合
     *
     * @param split 查询条件
     * @return 结果
     */
    @Override
    public SaleorderModel selectModelDataByModelIds(String[] split) {
        return saleorderMapper.selectModelByModelIds(split).get(0);

    }

    /**
     * 根据saleGoodsId 和saleorderModelId 查询 之前的执行数量和剩余数量
     *
     * @param hashMap
     * @return
     */
    @Override
    public SaleorderModel selectBatchModel(HashMap hashMap) {
        return saleorderMapper.selectBatchModel(hashMap);
    }

    /**
     * 通过销售订单子表主键查询销售订单子表数据
     *
     * @param saleorderModelId 销售订单子表主键
     * @return 结果
     */
    @Override
    public SaleorderModel selectSaleorderModelByModelId(Long saleorderModelId) {
        return saleorderMapper.selectSaleorderModelByModelId(saleorderModelId);
    }

    /**
     */
    /**
     * 查询是否生成销售订单的
     *
     * @param hashMap 查询条件
     * @return 结果
     */
    @Override
    public SaleorderOrder selectSaleorderByMap(HashMap<String, Object> hashMap) {
        return saleorderMapper.selectSaleorderByMap(hashMap);
    }

    @Override
    public SaleorderOrder selectSaleorderByIdMap(HashMap<String, Object> hashMap) {
        return saleorderMapper.selectSaleorderByIdMap(hashMap);
    }

    /**
     * 修改销售订单数据
     *
     * @param saleorderOrder 需要修改的数据
     * @return 结果
     */
    @Override
    public int updateSaleorderOrderIsAbandonment(SaleorderOrder saleorderOrder) {
        return saleorderMapper.updateSaleorder(saleorderOrder);
    }

    @Override
    public void updateStatus(List<Long> saleorders, String type) {
        // 1是批量废弃订单 2是批量确认付款

        for (int i = 0; i < saleorders.size(); i++) {
            SaleorderOrder saleorderOrder = saleorderMapper.selectUpdateStatus(saleorders.get(i));

            if (type.equals("1")) {
                if (saleorderOrder.getSaleorderStatus().equals("1")) {
                    saleorderOrder.setAbandonment("1");
                    saleorderMapper.updateStatus(saleorderOrder);
                }
            } else {
                if (saleorderOrder.getSaleorderStatus().equals("1")) {
                    saleorderOrder.setIsPay("1");
                    saleorderMapper.updateStatus(saleorderOrder);
                }


            }
        }

    }


    private ISaleGoodsService iSaleGoodsService;
    public SaleorderServiceImpl(ISaleGoodsService iSaleGoodsService) {
        this.iSaleGoodsService = iSaleGoodsService;
    }

    @Autowired
    private AuditService auditService;

    @Override
    public int auditSale(SaleorderOrder saleorderOrder) {
        // 先拿销售订单的编号
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("saleorderId", saleorderOrder.getSaleorderId());
        hashMap.put("deptId", SecurityUtils.getDeptId());
        SaleorderOrder saleorderOrder1 = selectSaleorderById(hashMap);

        // 根据销售订单的编号查询销货订单
        String saleorderNum = saleorderOrder1.getSaleorderNum(); // 销售订单的编号
        int count = iSaleGoodsService.selectSaleGoodsBySaleorderNum(saleorderNum);

        // 判断有无销货单
        if (count > 0) {
            throw new RuntimeException("当前订单已有销货单,不允许操作!");
        }

        // 审核时间
        saleorderOrder.setAuditTime(new Date());
        // 修改订单状态
        int result = saleorderMapper.auditSale(saleorderOrder);
        auditService.saleorderTopdf(saleorderOrder.getSaleorderId(), SecurityUtils.getDeptId());
        return result;
    }

    @Override
    public Long querypreviousId(Long saleorderId) {
        HashMap<String, Object> params = new HashMap<>();
        params.put("saleorderId", saleorderId);
        params.put("deptId", SecurityUtils.getDeptId());
        return saleorderMapper.querypreviousId(params);
    }

    @Override
    public Long queryNextId(Long saleorderId) {
        HashMap<String, Object> params = new HashMap<>();
        params.put("saleorderId", saleorderId);
        params.put("deptId", SecurityUtils.getDeptId());
         return saleorderMapper.queryNextId(params);
    }

    @Override
    public List<Map<String, Object>> pendingReview(Long deptID) {
        return saleorderMapper.pendingReview(deptID)
                .stream()
                .peek(item -> item.put("orderType", "销售订单"))
                .collect(Collectors.toList());
    }
}
